package com.xiaokong.changerecord.aop;

import cn.hutool.core.annotation.AnnotationUtil;
import com.xiaokong.changerecord.annotation.Change;
import com.xiaokong.changerecord.strategy.ChangeRecordStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

/**
 * 字段修改日志切面
 *
 * @author Hu_bx
 * @date 16:42 2022/11/9
 **/
@Slf4j
@Aspect
@RequiredArgsConstructor
public class ChangeRecordAspect {


    private final ChangeRecordStrategy changeRecordStrategy;


    /**
     * Controller层切点,注解方式
     */
    @Pointcut("@annotation(com.xiaokong.changerecord.annotation.Change)")
    public void controllerAspect() {

    }


    /**
     * 环绕处理
     *
     * @param joinPoint 切入点对象
     */
    @Around("controllerAspect()")
    public Object doAroundReturning(ProceedingJoinPoint joinPoint) throws Throwable {
        Object returnBody = joinPoint.proceed();
        try {
            // 出现异常,则保存失败,不处理修改记录
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Change change = AnnotationUtil.getAnnotation(methodSignature.getMethod(), Change.class);
            if (change.type().equals(Change.Type.CHANGE)) {
                changeRecordStrategy.createChangeDescribe(joinPoint, returnBody);
            } else {
                return changeRecordStrategy.createChangeRecord(joinPoint, returnBody);
            }
        } catch (Exception e) {
            log.error("生成变更记录失败，message = {}", e.getMessage(), e);
        }
        return returnBody;
    }


}
